import { defineStore } from 'pinia';
import { asyncRoutes } from '@/router';
import { RouteRecordRaw } from 'vue-router';
import { constantRoutes } from '@/router/modules/constant_routes';

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param permissions 从后端获取的权限列表 (['HomePage', 'UserPage', ...])
 */
function filterAsyncRoutes(routes: RouteRecordRaw[], permissions: string[]): RouteRecordRaw[] {
  const res: RouteRecordRaw[] = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (permissions.includes(tmp.name as string)) {
      if (tmp.children) {
        // 如果有子路由，递归过滤
        tmp.children = filterAsyncRoutes(tmp.children, permissions);
      }
      res.push(tmp);
    }
  });
  return res;
}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [] as RouteRecordRaw[], // 完整的、可访问的路由表
    addRoutes: [] as RouteRecordRaw[], // 动态添加的、有权限的路由表
  }),
  actions: {
    // 生成路由
    generateRoutes(permissions: string[]): Promise<RouteRecordRaw[]> {
      return new Promise(resolve => {
        // 筛选出有权限的异步路由
        const accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions);
        this.addRoutes = accessedRoutes;
        this.routes = constantRoutes.concat(accessedRoutes);
        resolve(accessedRoutes);
      });
    },
  },
});
